<?php

class servletAction extends BaseAction {

    public function  execute() {
        $this->uhash    = $this->params['uhash'];
        $this->key    = $this->params['app_key'];
        $this->auth     = 0;
        if(!array_key_exists('user', $_SESSION)){
            $this->uid    = 0;
        }else{
            $this->uid    = $_SESSION['user']['id'];
        }
        if(empty($this->uhash) && $this->auth) {
            $key    = $this->getAppKey();
            if(!in_array($this->key, $key)) {
                echo 'app_key error please refresh page!';
                exit;
            }
        }
        $this->view->layout = '';
        parent::execute();
    }
    //检查权限
    private function is_public($uhash) {

        if(empty($uhash)) {
            echo '暂时没有统计数据';
            exit;
        }

        //$key    = 'url_public_'.$uhash;

        $public = null ;
        //        $cache  = MemcacheAction::getCache();
        //        $public = $cache->get($key);
        if(!$public) {
            $rs = DAO_Finder::findOne(DB_URL, array('uhash' => $uhash), 'status,uid');
            if(!$rs) {
                //$cache->set($key, 'error');
                echo '该短网址不存在';
                exit;
            }
            $uid    = $rs->getUid();
            //$cache->set($key, $public, 3600);
            $public = trim($rs->getStatus());
            if($public !='public' && $uid != $_SESSION['user']['id']) {
                echo '该网址设置保密';
                exit;
            }
        }
        if($public =='error') {
            echo '该短网址不存在';
            exit;
        }

    }
    /**
     * 返回验证码
     * @return <type>
     */
    public function getAppKey(){
        $key_mid    = strtotime(date('Y-m-d H:00:00'));
        $key_pre    = $key_mid - 3600;
        $key_las    = $key_mid + 3600;
        return array(md5($key_mid), md5($key_las), md5($key_pre));
    }
    /**
     * 月统计
     */
    public function actionMonthCount() {
        $uhash  = $this->params['uhash'];
        if(empty($uhash)) {
            echo '暂时没有统计数据';
            exit;
        }

        $ip_key = 'month_count_ip_'.$uhash;
        $pv_key = 'month_count_pv_'.$uhash;
        $y1_key = 'month_count_day_'.$uhash;
//        $mem    = MemcacheAction::getCache();
//
//        $ip     = $mem->get($ip_key);
//        $pv     = $mem->get($pv_key);
//        $y1     = $mem->get($y1_key);
        $ip = null;
        if(!$ip){
            
            load_help('DateTime');
            $id = $this->params['id'];
            $time_stamp = 3600*24 *10;
            $hour   = getMonthCount($time_stamp, '-');
            asort($hour);
            //获取pv
            foreach ($hour as $k=>$v):
                $y1[]   =  date('d',$v['start']);
                $pv[]   = DB_ACCESS::getPv($uhash, $v['start'], $v['end']);
                $ip[]   = DB_IP::getIp($uhash, $v['start'], $v['end']);
                //echo date('Y-m-d H:i:s',$v['start']).'--'.date('Y-m-d H:i:s',$v['end']).'<br/>';
            endforeach;
            $life    = 3600*24*3;
//            $mem->set($ip_key, $ip, $life);
//            $mem->set($pv_key, $pv, $life);
//            $mem->set($y1_key, $y1, $life);
        }
        $this->set('ip',  '['.implode(',', $ip).']');
        $this->set('pv',  '['.implode(',', $pv).']');
        $this->set('y1',  '['.implode(',', $y1).']');
        $this->render('hour_count');
    }
    /**
     *日统计
     */
    public function actionHourCount() {
        $uhash  = $this->params['uhash'];
        if(empty($uhash)) {
            echo '暂时没有统计数据';
            exit;
        }

        $ip_key = 'hour_count_ip_'.$uhash;
        $pv_key = 'hour_count_pv_'.$uhash;
        $y1_key = 'hour_count_day_'.$uhash;
        $mem    = MemcacheAction::getCache();

        $ip     = $mem->get($ip_key);
        $pv     = $mem->get($pv_key);
        $y1     = $mem->get($y1_key);

        
        $this->view->layout = '';
        $pv = array();
        $ip = array();
        if(!$ip){
            load_help('DateTime');
            $hour   = getHourCount(3600*5,'-',12);
            asort($hour);
            //获取pv
            foreach ($hour as $k=>$v):
                $date   = date('G',$v['start']);
                if ($date==0) {
                    $date   = 24;
                }
                $y1[]   =  $date;
                $pv[]   = DB_ACCESS::getPv($uhash, $v['start'], $v['end']);
                $ip[]   = DB_IP::getIp($uhash, $v['start'], $v['end']);
            endforeach;
        }
        $this->set('ip',  '['.implode(',', $ip).']');
        $this->set('pv',  '['.implode(',', $pv).']');
        $this->set('y1',  '['.implode(',', $y1).']');
        $this->render();
    }

    /**
     * 来路统计
     */
    public function actionRefererCount() {
        $uhash  = $this->params['uhash'];
        $this->is_public($uhash);
        
        $key    = 'referer_count'.$uhash;
//        $mem    = MemcacheAction::getCache();
//        $rs     = $mem->get($key);
        $rs = null;
        if(!$rs || $rs) {
            $this->view->layout = '';
            $sql    = "SELECT * , count( id ) AS count FROM `u22_access` WHERE uhash='$uhash' GROUP BY referer order by id desc limit 0,30 ";
            $rs = DAO_Finder::result($sql);
            if(empty($rs)) {
                echo '暂无数据';
                exit;
            }
            //$mem->set($key, $rs,3600);
        }

        $this->set('rs', $rs);
        $this->render();
    }
    
    /**
     * 操作系统统计
     */
    public function actionOsCount() {

        $uhash  = $this->params['uhash'];
        $key    = 'os_'.$uhash;
        $mem  = MemcacheAction::getCache();
        $arr    = $mem->get($key);
        if(!$arr) {
            $rs     = DAO_Finder::find(DB_URL_OS, array('uhash'=>$uhash), 'name,click');

            $arr    = array();
            if(!$rs){
                echo '暂无统计信息';
                exit;
            }
            foreach ($rs as $k => $v):
                $v  = $v->getArray();
                if(empty($v['name'])) {
                    $v['name']   =0;
                }
                if(empty($v['click'])) {
                    $v['click']   =0;
                }
                $arr[]    = "['".$v['name']."',".$v['click']."]";
            endforeach;
            $mem->set($key, $arr,3600);
        }
        $this->set('show', implode(',', $arr));
        $this->render();
    }

    /**
     * 浏览器统计
     */
    public function actionIeCount() {
        $uhash  = $this->params['uhash'];
        $key    = 'ie_'.$uhash;
        $mem  = MemcacheAction::getCache();
        $arr    = $mem->get($key);
        if(!$arr) {
            $rs     = DAO_Finder::find(DB_URL_IE, array('uhash'=>$uhash), 'name,click');

            $arr    = array();
            if(!$rs){
                echo '暂无统计信息';
                exit;
            }
            foreach ($rs as $k => $v):
                $v  = $v->getArray();
                if(empty($v['name'])) {
                    $v['name']   =0;
                }
                if(empty($v['click'])) {
                    $v['click']   =0;
                }
                $arr[]    = "['".$v['name']."',".$v['click']."]";
            endforeach;
            $mem->set($key, $arr,3600);
        }
        $this->set('show', implode(',', $arr));
        $this->render();
    }

    public function actionProvinceCount() {
        $uhash  = $this->params['uhash'];
        $key    = 'province_'.$uhash;
//        $mem  = MemcacheAction::getCache();
//        $rs   = $mem->get($key);
        $rs = null;
        if(!$rs) {
            $rs = DAO_Finder::find(DB_URL_PROVINCE, array('uhash' =>$uhash));
            if(!$rs){
                echo '暂无统计信息';
                exit;
            }
            //$mem->set($key, $rs ,  3600);
        }

        $this->set('rs', $rs);
        $this->render();
    }
    
    public function actionSpiderCount() {
        $uhash  = $this->params['uhash'];
        $key    = 'spider_'.$uhash;
//        $mem  = MemcacheAction::getCache();
//        $rs   = $mem->get($key);
        $rs = null;
        if(!$rs) {
            $rs = DAO_Finder::find(DB_URL_SPIDER, array('uhash' =>$uhash));
            if(!$rs){
                echo '暂无统计信息';
                exit;
            }
            //$mem->set($key, $rs ,  3600);
        }

        //$this->set('rs', $rs);
        $this->render('province_count');
    }

    /**
     * 添加短网址
     */
    public function actionAddUrl() {
        set_time_limit(0);
        $url    = $this->postVar('url');
        $custom = $this->postVar('custom');
        $guest  = $this->postVar('guest');
        $return = array();
        if(!array_key_exists('user', $_SESSION)){
            $uid    = 0;
        }else{
            $uid    = $_SESSION['user']['id'];
        }

        if($url) {

            //保存信息
            $save   = DB_URL::add($url,0, $uid);
            if(strlen($url) > 40) {
                $url    = substr($url, 0,40).'...';
                $save->setUrl($url);
            }
            //保存自定义后缀
            if(array_key_exists('user', $_SESSION)){
                if($_SESSION['user']['is_custom'] ||$custom) {
                    $has    = DB_URL::checkUhash($uhash);
                    if(!$has){
                        $save->setUhash($custom);
                        $save   = $save->save();
                    }
                }
            }
            $return['u22']  = $save->getUhash();
            $return['code'] = 'ok';

            //访客选项
            if(!$this->uid){
                $_SESSION['uhash']    = $return['u22'];
                $this->actionGuestUrlAdd();
            }
            
            echo json_encode($return);
            exit;
        }else{
            echo json_encode(array('code'=>'error','msg'=>'添加失败','act' =>1));
            exit;
        }
        echo json_encode(array('code'=>'error','msg'=>'非法参数','act' =>1));
    }
    /**
     * 添加短网址
     */
    public function actionAddUrlBak() {
        $last_add   = $_SESSION['add_time'];

        if((time()-$last_add)<10) {
            echo json_encode(array('code'=>'error','msg'=>'添加频率过快','url'=>base64_encode($url)));
        }
        $url    = $this->postVar('url');
        $custom = $this->postVar('custom');
        $guest  = $this->postVar('guest');
        $return = array();
        if(!array_key_exists('user', $_SESSION)){
            $uid    = 0;
        }else{
            $uid    = $_SESSION['user']['id'];
        }

        if($url) {
            //获取腾讯短网址
            get_block('home', 'get_tencent_url',array('url'=>$url));
            $return['tencent'] = $_SESSION['tencent_url'];
            if(!array_key_exists('tencent_url', $_SESSION)){
                echo json_encode(array('code'=>'error','msg'=>'已存在该腾讯短网址','url'=>base64_encode($url)));
                exit;
            }

            //获取新浪短网址
            $baseUrl = 'http://'.$_SERVER['HTTP_HOST'].'/cgi/sina/short_url.php?q=' . base64_encode($url);

            $return['sina'] =  trim(file_get_contents($baseUrl));

            $_SESSION['sina_url']   = $return['sina'];
            if(strlen($return['sina']) != 6 ){
                echo json_encode(array('code'=>'error','msg'=>'已存在该新浪短网址','url'=>base64_encode($url)));
                exit;
            }elseif(strlen($_SESSION['tencent_url']) !=6){
                 echo json_encode(array('code'=>'error','msg'=>'已存在该腾讯短网址','url'=>base64_encode($url)));
                 exit;
            }
            //保存信息
            $save   = DB_URL::add($url,0, $uid);
            //保存自定义后缀
            if(array_key_exists('user', $_SESSION)){
                if($_SESSION['user']['is_custom'] ||$custom) {
                    $has    = DB_URL::checkUhash($uhash);
                    if(!$has){
                        $save->setUhash($custom);
                        $save   = $save->save();
                    }
                }
            }
            $return['u22']  = $save->getUhash();
            $return['code'] = 'ok';

            //访客选项
            if(!$this->uid){
                $_SESSION['uhash']    = $return['u22'];
                $this->actionGuestUrlAdd();
            }

            //清除会员url
            if(!$guest) {
                unset($_SESSION['cache']['my_url_list']);
            }
            $_SESSION['add_time']   = time();
            echo json_encode($return);
            exit;
        }else{
            echo json_encode(array('code'=>'error','msg'=>'添加失败','act' =>1));
            exit;
        }
        echo json_encode(array('code'=>'error','msg'=>'非法参数','act' =>1));
    }
    /**
     * 未登陆停止;
     */
    private function checkLogin() {
        if(empty($_SESSION['user'])){
            exit;
        }
    }

    /**
     * 我的短网址
     */
    public function actionMyUrlList(){
        $tm          = array();
        $sina_show   = false;
        $uid    = $_SESSION['user']['id'];
        $page = empty($this->params['page']) ? 1 : $this->params['page'];
        $pagelimit = empty($this->params['limit']) ? 10 : $this->params['limit'];
        $offset = ($page - 1) * $pagelimit;
        $sina   = $this->params['sina'];
        $where  = array('uid'=>$uid);


        if(!empty($sina)) {
            $where  = '';
            $where  = "uid=$uid and sina_url !=''";
        }
        if(array_key_exists('sina', $this->params)) {
            $sina_show   = true;
        }


        $rs     = DAO_Finder::daoAll(DB_URL, $where, 'id,uid,uhash,sina_url,tencent_url,title,total_pv,total_ip,url','id desc', "$offset, $pagelimit");
        
        $total  = DAO_Finder::findCount(DB_URL, $where);
        $pager  = new Pager('javascript:get_my_url_list(', $total, $pagelimit,');');
        $pager->SetCurPage($page);
        
        //print_r($rs);
        $arr    = array();
        
        if($rs) {
            $log_time   = date('Ymd');
            foreach ($rs as $k => $v) {
                $uhash  = $v->getUhash();
                
                if($sina_show) {
                    $tm['comment']  = DB_SHORT_URL_COMMENT_COUNTS::showTotal($uhash);
                    $tm['share']  = DB_SHORT_URL_SHARE_COUNTS::showTotal($uhash);
                }
                
                //今日ip
                $ip    = DAO_Finder::findOne(DB_COUNT_IP, array('uhash'=>$uhash), 'log_time', 'id desc');
                
                //今日pv
                $pv    = DAO_Finder::findOne(DB_COUNT_PV, array('uhash'=>$uhash), 'log_time', 'id desc');
                
                $tmp    = $v->getArray();
                if(strlen($tmp['url']) > 40) {
                    $tmp['url'] = substr($tmp['url'], 0, 40).'...';
                }
                //获取今日ip
                if(!$ip){
                    $tmp['ip']  = 0;
                }else{
                    $tmp['ip'] = $ip->getLogTime();
                }

                //获取pv
                if(!$pv){
                    $tmp['pv']  = 0;
                }else{
                    $tmp['pv'] = $pv->getLogTime();
                }
                $arr[]  = array_merge($tm, $tmp);
                unset($tmp);
            }
        }else{
            echo json_encode(array('code' => 'ok', 'msg' => '您还没有添加短网址','data'=>''));
            exit;
        }
        echo json_encode(array('code' => 'ok', 'data' => $arr, 'page'=>$pager->GetNavigation()));
    }

    //游客添加短
    function actionGuestUrlAdd() {
        $uhash  = $_SESSION['uhash'];
        //不存在
        if(!$uhash) {
            exit;
        }

        if(array_key_exists('guest_url', $_SESSION)) {
            $url    = $_SESSION['guest_url'];
        }else{
            $url    = array();
        }
        
        $rs = DAO_Finder::findOne(DB_URL, array('uhash' => $uhash));
        //没记录;
        if(!$rs) {
            exit;
        }
        $tmp    = $rs->getArray();
        //获取今日ip
        $ip = DAO_Finder::findOne(DB_COUNT_IP, array('uhash'=>$uhash), 'log_time', 'id desc');
        if(!$ip){
            $tmp['ip']  = 0;
        }else{
            $tmp['ip']  = $ip->getIp();
        }
        //获取今日pv
        $pv = DAO_Finder::findOne(DB_COUNT_PV, array('uhash'=>$uhash), 'log_time', 'id desc');
        if(!$pv){
            $tmp['pv']  = 0;
        }else{
            $tmp['pv']  = $ip->getPv();
        }
        //$_SESSION['guest_url'][]   = $tmp;
        Cookies::setMine($uhash);
        unset($_SESSION['uhash']);
    }

    public function actionGuestUrlList() {
        $rs = Cookies::getMine('u22_url');
        //$rs = "'". str_replace(',', "','", $rs) ."'";
        $rs = explode(',', $rs);
        $cb = array();
        $w  = null;
        if(count($rs) > 0) {
            for($i=0;$i<count($rs);$i++) {
                $cb[]   = '?';
            }
            $w  = implode(',', $cb);
        }
        $sql    = "select * from {#prefix#}url where uhash in (". $w.")";
        $re = DAO_Finder::result($sql, DB_URL, $rs);
        $this->set('rs', $re);
        $this->render();
    }
    /**
     * 我的短网址数量
     */
    public function actionTotalUrl(){
        $total  = DAO_Finder::findCount(DB_USER, array('uid' => $_SESSION['user']['id']));
        echo $total;
    }

    /**
     * 新浪短网址缩短
     */
    function actionSinaUrl() {
        $q  = base64_decode($this->params['url']);
        if($q) {
            $dir    = ROOT . '/cgi/sina/';
            include_once( $dir . 'config.php' );
            include_once( $dir . 'weibooauth.php' );
            $c = new WeiboClient( WB_AKEY , WB_SKEY ,  token_key, token_secret);
            $ms  = $c->home_timeline(); // done
            $me = $c->verify_credentials();
            $result = $c->update($q);
            if(!array_key_exists('text', $result)) {
                if(strstr('?', $q)) {
                    $q  .= '&rand='.rand(0, 9999).time();
                }else{
                    $q  .= '?radn='.rand(0, 9999).time();
                }
                $result = $c->update($q);
            }
            $rs = str_replace('http://t.cn/', '', $result['text']);
            echo  $rs;
        }
    }

    /**
     * 新版腾讯短网址添加
     */
    public function actionTencentUrl() {
        $q  = base64_decode($this->params['url']);
        $dir    = ROOT . '/cgi/tencent/';
        @require_once($dir.'config.php');
        @require_once($dir.'oauth.php');
        @require_once($dir.'opent.php');
        @require_once($dir.'api_client.php');
        $c = new MBApiClient(MB_AKEY , MB_SKEY , token_key , token_secret);
        $text   = $q;
        $p =array(
            'c' => $text,
            'ip' => $_SERVER['REMOTE_ADDR'],
            'j' => '',
            'w' => '',
            'type' => 1,
            'r' => time()
        );
        $result = $c->postOne($p);
        $re = $this->_tencentUrlAddExt($c, $result);
        while(is_array($re) && $re !=='频率受限!') {
            $re = $this->_tencentUrlAddExt($c, $result);
        }
        echo  $re;
    }

    private function _tencentUrlAddExt($c, $result) {
      if(array_key_exists('error', $result) && $result['error'] =='频率受限!') {
          return '频率受限!';
      }
      if(array_key_exists('errcode', $result) && $result['errcode'] == 0){
            $id =  $result['data']['id'];
            $p  = array('id' =>$id);
            $result = $c->getOne($p);
            if($result['errcode'] == 0){
                return  str_replace('http://url.cn/', '', $result['data']['origtext']);
            }
         //有错误产生
        }else{
            if(strstr('?', $q)) {
                $q  .= '&rand='.rand(11111, 999999999999999).time();
            }else{
                $q  .= '?radn='.rand(111, 999999999999999).time();
            }
           $p =array(
                'c' => $q,
                'ip' => $_SERVER['REMOTE_ADDR'],
                'j' => '',
                'w' => '',
                'type' => 1,
                'r' => time()
            );
            $result = $c->postOne($p);
            //$this->actionTencentUrlAddExt($c, $result);
            return $result;
        }
    }
        
}

